package com.zlq.cn.controller.api;


import com.zlq.cn.annotations.UnLogin;
import com.zlq.cn.api.ApiCodeEnum;
import com.zlq.cn.api.ApiMessage;
import com.zlq.cn.api.ApiParam;
import com.zlq.cn.api.ResponseException;
import com.zlq.cn.config.FinderConfiguration;
import com.zlq.cn.entity.SmsRecord;
import com.zlq.cn.service.un.SmsRecordService;
import com.zlq.cn.service.un.UserService;
import com.zlq.cn.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;

/**
 * <p>
 * 短信记录 前端控制器
 * </p>
 *
 * @author zhoucl
 * @since 2020-08-24
 */
@RestController
@RequestMapping("/api/sms")
public class SmsRecordController {
    @Autowired
    private SmsRecordService smsRecordService;
    @Autowired
    private UserService userService;
    @Autowired
    private FinderConfiguration finderConfiguration;

//    @RequestMapping("/sendNewSms")
    @UnLogin
    public Object sendSms(@RequestBody ApiParam apiParamData,
                          HttpServletRequest request,
                          @NotNull(message = "验证码类型不能为空") String smsType,
                          @NotNull(message = "手机号码不能为空") String phone) throws Exception {
        //        User user = userService.getOne(new QueryWrapper<User>().eq("phone", phone));
//        if (IpUtil.checkIp(IpUtil.getClientIpAddress(request))) {
//            return ApiMessage.resultApiMessage("发送成功");
//        }
        if (FinderConfiguration.DEV.equals(finderConfiguration.getProfile())) {
            return ApiMessage.resultApiMessage("发送成功");
        }
        String vcode = StringUtils.getRandomByLength(4);
        if (SmsRecord.SMS_TYPE_LOGIN.equals(smsType)) {

        } else {
            ResponseException.resultApiError("该短信类型不存在");
        }
        SmsRecord smsRecord = new SmsRecord();
        smsRecord.setType(smsType);
        smsRecord.setVcode(vcode);
        smsRecord.setSendtime(LocalDateTime.now());
        smsRecord.setBuildtime(LocalDateTime.now());
        smsRecord.setEndtime(LocalDateTime.now().plusMinutes(5));
        smsRecord.setMobile(phone);
        try {
            smsRecord.setMsg(smsRecordService.sendSms(phone, vcode));
            smsRecord.setStatus(1);
            smsRecordService.save(smsRecord);
            return ApiMessage.resultApiMessage("发送成功");
        } catch (Exception e) {
            smsRecord.setMsg("短信发送失败");
            if (e instanceof ResponseException) {
                smsRecord.setMsg(((ResponseException) e).getMsg());
            }
            smsRecord.setStatus(-1);
            //smsRecordService.save(smsRecord);
            throw new ResponseException(ApiCodeEnum.API_ERROR.getCode(), "短信发送失败");
        }
    }
}

